package com.tongzhan.service;

import com.tongzhan.base.BaseCriteria;
import com.tongzhan.base.BaseShareService;
import com.tongzhan.consts.SysDictTypeKeyConst;
import com.tongzhan.entity.MarkPrompt;
import com.tongzhan.entity.User;
import com.tongzhan.entity.party.WorkInfo;
import com.tongzhan.entity.party.WorkSchedule;
import com.tongzhan.utils.ThreadLocalUtil;
import com.tongzhan.vo.WorkInfoVo;
import com.tongzhan.vo.WorkScheduleVo;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author htmic
 * @date 2020/7/29
 */
@Service
public class WorkService extends BaseShareService {

    /**
     * 工作安排列表
     * @param partyTypeId
     * @param page
     * @param size
     * @return
     */
    public Page<WorkInfo> workList(Integer partyTypeId, Integer page, Integer size) {
        Criteria criteria = BaseCriteria.where("is_del").is(0);
        if(partyTypeId!=null){
            criteria.and("partyTypeId").is(partyTypeId);
        }
        Query query = new Query(criteria);
        PageRequest of = PageRequest.of(page, size, Sort.Direction.DESC, "time");
        if (ThreadLocalUtil.getThreadLocal().getDutiesCode().equals(ThreadLocalUtil.STREET_CODE)) {
            query.addCriteria(BaseCriteria.where("streetCode").like(ThreadLocalUtil.getThreadLocal().getStreetCode()));
        }
        if (ThreadLocalUtil.getThreadLocal().getDutiesCode().equals(ThreadLocalUtil.VILLAGE_CODE)) {
            query.addCriteria(BaseCriteria.where("villageCode").like(ThreadLocalUtil.getThreadLocal().getVillageCode()));
        }
        Page<WorkInfo> all = workInfoRepository.findPage(query, of);
        if (!CollectionUtils.isEmpty(all.getContent())) {
            all.getContent().forEach(item->{
                item.setPartyTypeName(sysDictService.getValueByType(SysDictTypeKeyConst.PUBLIC_PARTY_TYPE, item.getPartyTypeId()));
            });
        }
        return all;
    }

    /**
     * 工作安排详情
     * @param id
     * @return
     */
    public WorkInfoVo workDetail(String id,String userId) {
        WorkInfo work = workInfoRepository.findByPrimaryKey(id);
        if (work != null) {
            WorkInfoVo result = new WorkInfoVo();
            BeanUtils.copyProperties(work, result);
            result.setPartyTypeName(sysDictService.getValueByType(SysDictTypeKeyConst.PUBLIC_PARTY_TYPE, result.getPartyTypeId()));
            //查询安排记录
            Query query = new Query(BaseCriteria.where("is_del").is(0).and("workId")
                    .is(id)).with(Sort.by(Sort.Direction.ASC, "addTime"));;
            List<WorkSchedule> list =  workScheduleRepository.findAll(query);
            if (!CollectionUtils.isEmpty(list)) {
                List<WorkScheduleVo> listVo = new ArrayList<>(list.size());
                list.forEach(item->{
                    WorkScheduleVo vo = new WorkScheduleVo();
                    BeanUtils.copyProperties(item, vo);
                    listVo.add(vo);
                });
                result.setList(listVo);
            }
            //标记角标已读
            markPromptService.read(id,userId);
            return result;
        }
        return null;
    }

    /**
     * 新增
     * @param work
     * @param list
     * @return
     */
    @Transactional( rollbackFor = Exception.class)
    public long addSchedule(WorkInfo work, List<WorkSchedule> list) {
        //添加工作
        work.setIs_del(0);
        work.setAddTime(new Date());
        User userById = findUserById(work.getAddUserId());
        if(userById!=null){
            work.setAddUserName(userById.getUserName());
        }
        work.setStreetCode(ThreadLocalUtil.getThreadLocal().getStreetCode());
        work.setVillageCode(ThreadLocalUtil.getThreadLocal().getVillageCode());
        long flag = workInfoRepository.insertSelective(work);
        if(flag<=0){
            throw new RuntimeException("插入失败");
        }

        //添加安排
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item->{
                item.setWorkId(work.getId());
                item.setType(1);
                item.setIs_del(0);
                item.setAddTime(new Date());
            });

            List<WorkSchedule> result = workScheduleRepository.saveAll(list);
            if(result.size()!=list.size()){
                return 0;
            }
        }
        //添加角标
        markPromptService.add(new MarkPrompt(3, work.getId()),"12");
        return 1;
    }
}
